using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

using GameEngine.Cameras;
using GameEngine.Content;
using GameEngine.Shaders;

namespace GameEngine.Content
{
    public class GEModel : GEObject, IGERenderable, IGEHasContent
    {
        private string asset;
        private Model model;

        public GEModel(string asset)
        {
            this.asset = asset;
        }

        public new void LoadContent(ContentManager content)
        {
            model = content.Load<Model>(asset);
        }

        public void Render(GraphicsDevice device)
        {
            GEShader effect = GEShaderManager.GetShader(Shader);

            effect.Effect.Parameters["WorldViewProjection"].SetValue(GECameraManager.ActiveCamera.World * GECameraManager.ActiveCamera.View * GECameraManager.ActiveCamera.Projection);

            for (int i = 0; i < model.Meshes.Count; i++)
            {
                device.Indices = model.Meshes[i].IndexBuffer;

                effect.Effect.Begin();

                foreach (EffectPass pass in effect.Effect.CurrentTechnique.Passes)
                {
                    pass.Begin();

                    for (int ii = 0; ii < model.Meshes[i].MeshParts.Count; ii++)
                    {
                        device.VertexDeclaration = model.Meshes[i].MeshParts[ii].VertexDeclaration;
                        device.Vertices[0].SetSource(model.Meshes[i].VertexBuffer, model.Meshes[i].MeshParts[ii].StreamOffset, model.Meshes[i].MeshParts[ii].VertexStride);

                        effect.Effect.Parameters["xTexture"].SetValue(((BasicEffect)model.Meshes[i].MeshParts[ii].Effect).Texture);

                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                            model.Meshes[i].MeshParts[ii].BaseVertex,
                            0, model.Meshes[i].MeshParts[ii].NumVertices,
                            model.Meshes[i].MeshParts[ii].StartIndex,
                            model.Meshes[i].MeshParts[ii].PrimitiveCount);
                    }

                    pass.End();
                }

                effect.Effect.End();
            }
        }
    }
}
